// -----------------------------------------------
// Author:     code34 nicolas_boiteux@yahoo.fr
// Edited by:  Neumatic
// Warcontext: Walker civilian
// -----------------------------------------------

private [
	"_position",
	"_positions",
	"_index",
	"_allunits",
	"_civil",
	"_group",
	"_buildings"
];

_group = _this select 0;

_allunits = [];
_positions = [];

_group setCombatMode "RED";
_group allowFleeing 0;
_group setSpeedMode "limited";

{
	_x setBehaviour "safe";
	_x allowFleeing 0;
	_x setVariable ["lastpos", position _x, false];
	_x setVariable ["destination", position _x, false];
	_x setVariable ["moveretry", 0, false];
	_x setUnitPos "UP";
} foreach (units _group);

_position = position (leader _group);
_buildings = nearestObjects [_position, ["Building"], 500];
sleep 1;

{
	_index = 0;
	while {format ["%1", _x buildingPos _index] != "[0,0,0]"} do {
		_position = _x buildingPos _index;
		_positions = _positions + [_position];
		_index = _index + 1;
	};
} foreach _buildings;

while {count (units _group) > 0} do {
	if (count _allunits == 0) then {
		_allunits = units _group;
	};

	_civil = _allunits select 0;
	_allunits = _allunits - [_civil];

	// Exclude all non civilian
	if (_civil getVariable "civilrole" == "civil") then {
		if (position _civil distance (_civil getVariable "destination") < 8) then {
			_position = _positions call BIS_fnc_selectRandom;
			_civil setVariable ["destination", _position, false];
			_civil stop false;
			_civil doMove _position;
			_civil setVariable ["moveretry", 0, false];
		} else {
			_civil stop false;
			_civil doMove (_civil getVariable "destination");
		};

		if (format ["%1", _civil getVariable "lastpos"] == format ["%1", position _civil]) then {
			_civil setVariable ["moveretry", (_civil getVariable "moveretry") + 1, false];
		};

		_civil setVariable ["lastpos", position _civil, false];

		if(_civil getVariable "moveretry" > 3) then {
			_position = _positions call BIS_fnc_selectRandom;
			_civil stop false;
			_civil setVariable ["destination", _position, false];
			_civil doMove _position;
			_civil setVariable ["moveretry", 0, false];
		};
		sleep 5;
	};
};